/**
 * UI渲染模块
 */
import { API_BASE_URL } from './config.js';
import { state } from './state.js';

/**
 * 渲染职业类型Tab
 */
export const renderProfessionTabs = () => {
  const container = document.getElementById('professionContainer').querySelector('div');
  container.innerHTML = '';
  
  if (state.professionLoading) {
    const loading = document.createElement('div');
    loading.className = 'text-center text-gray-500 py-2';
    loading.textContent = '加载职业类型中...';
    container.appendChild(loading);
    return;
  }
  
  state.professionList.forEach((profession, index) => {
    const tab = document.createElement('div');
    tab.className = `profession-tab ${state.selectedProfessionIndex === index ? 'active' : ''}`;
    tab.textContent = profession;
    tab.onclick = () => {
      // 导入 handleProfessionClick
      import('./handlers.js').then(({ handleProfessionClick }) => {
        handleProfessionClick(index);
      });
    };
    container.appendChild(tab);
  });
};

/**
 * 显示/隐藏加载指示器
 */
export const setLoading = (loading) => {
  state.loading = loading;
  const indicator = document.getElementById('loadingIndicator');
  if (loading) {
    indicator.classList.remove('hidden');
  } else {
    indicator.classList.add('hidden');
  }
};

/**
 * 渲染第一级Tab
 */
export const renderLevel1 = () => {
  const container = document.getElementById('level1Container').querySelector('div');
  container.innerHTML = '';
  
  state.level1List.forEach((item, index) => {
    const tab = document.createElement('div');
    tab.className = `flex-center px-6 pt-2 rounded-t-xl cursor-pointer transition-all ${
      state.activeLevel1 === index 
        ? 'bg-white text-blue-500 font-bold translate-y-1 pt-3 pb-4 tab-active' 
        : 'text-gray-500 translate-y-2'
    }`;
    tab.textContent = item.title || item.departName || item.name || '未知';
    tab.onclick = () => {
      import('./handlers.js').then(({ handleTabClick }) => {
        handleTabClick(item, 1, index);
      });
    };
    
    container.appendChild(tab);
  });
};

/**
 * 渲染第二级Tab
 */
export const renderLevel2 = () => {
  const container = document.getElementById('level2Container');
  container.innerHTML = '';
  
  state.level2List.forEach((item, index) => {
    const tab = document.createElement('div');
    tab.className = `flex items-center border-l-4 border-l-solid px-2 py-2 whitespace-nowrap cursor-pointer transition-all ${
      state.activeLevel2 === index
        ? 'border-green-500 bg-white text-green-500 font-bold vertical-tab-active'
        : 'border-transparent text-gray-500'
    }`;
    tab.textContent = item.title || item.departName || item.name || '未知';
    tab.onclick = () => {
      import('./handlers.js').then(({ handleTabClick }) => {
        handleTabClick(item, 2, index);
      });
    };
    
    container.appendChild(tab);
  });
};

/**
 * 渲染第三级Tab
 */
export const renderLevel3 = () => {
  const container = document.getElementById('level3Container').querySelector('div');
  container.innerHTML = '';
  
  state.level3List.forEach((item, index) => {
    const btn = document.createElement('button');
    btn.className = `px-4 py-2 text-sm rounded whitespace-nowrap transition-all ${
      state.activeLevel3 === index
        ? 'bg-green-500 text-white btn-active'
        : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
    }`;
    btn.textContent = item.title || item.departName || item.name || '未知';
    btn.onclick = () => {
      import('./handlers.js').then(({ handleTabClick }) => {
        handleTabClick(item, 3, index);
      });
    };
    
    container.appendChild(btn);
  });
};

/**
 * 获取护士头像
 */
export const getNurseAvatar = (avatar) => {
  console.log('getNurseAvatar', avatar);
  if (avatar) {
    // 如果头像URL是相对路径，拼接API基础URL
    if (avatar.startsWith('http')) {
      return avatar;
    } else {
      return `https://anfine.huasun-healthcare.com/api-ah/${avatar}`;
    }
  }
  // 默认头像
  return 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="80" height="80"%3E%3Crect width="80" height="80" fill="%23909090"/%3E%3Ctext x="50%25" y="50%25" text-anchor="middle" dy=".3em" fill="white" font-size="32"%3E%3F%3C/text%3E%3C/svg%3E';
};

/**
 * 更新内容区
 */
export const updateContentArea = () => {
  const contentArea = document.getElementById('contentArea');
  
  // 调试日志
  console.log('updateContentArea 状态:', {
    nurseLoading: state.nurseLoading,
    loading: state.loading,
    hasCurrentItem: !!state.currentLevel3Item,
    nurseListLength: state.nurseList?.length || 0
  });
  
  // 加载状态：只有在加载护士列表时才显示加载中
  // 目录加载状态不应该影响内容区的显示
  if (state.nurseLoading) {
    contentArea.innerHTML = `
      <div class="text-center py-8">
        <div class="inline-block animate-spin rounded-full h-6 w-6 border-b-2 border-blue-500 mb-2"></div>
        <p class="text-gray-500">加载中...</p>
      </div>
    `;
    return;
  }
  
  if (state.currentLevel3Item) {
    // 如果有选中项，显示护士列表
    if (state.nurseList && state.nurseList.length > 0) {
      const nurseGrid = document.createElement('div');
      nurseGrid.className = 'nurse-grid';
      
      state.nurseList.forEach((nurse) => {
        const card = document.createElement('div');
        // 检查是否已选中（使用state中的selectedNurses）
        const selected = state.selectedNurses.some(item => item.id === nurse.id);
        card.className = `nurse-card ${selected ? 'selected' : ''}`;
        card.onclick = () => {
          import('./handlers.js').then(({ handleNurseClick }) => {
            handleNurseClick(nurse);
          });
        };
        
        const avatar = document.createElement('img');
        avatar.className = 'nurse-avatar';
        avatar.src = getNurseAvatar(nurse.avatar);
        avatar.alt = nurse.name || '未知';
        avatar.onerror = function() {
          this.src = 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="80" height="80"%3E%3Crect width="80" height="80" fill="%23909090"/%3E%3Ctext x="50%25" y="50%25" text-anchor="middle" dy=".3em" fill="white" font-size="32"%3E%3F%3C/text%3E%3C/svg%3E';
        };
        
        const name = document.createElement('div');
        name.className = 'nurse-name';
        name.textContent = nurse.name || '未知';
        
        card.appendChild(avatar);
        card.appendChild(name);
        nurseGrid.appendChild(card);
      });
      
      contentArea.innerHTML = '';
      contentArea.appendChild(nurseGrid);
    } else {
      // 空数据状态
      const currentJob = state.professionList[state.selectedProfessionIndex] || state.professionList[0] || '数据';
      contentArea.innerHTML = `
        <div class="text-center text-gray-500 py-8">
          <p>暂无${currentJob}数据</p>
        </div>
      `;
    }
  } else {
    contentArea.innerHTML = `
      <div class="text-center text-gray-500 py-8">
        请选择三级目录项查看内容
      </div>
    `;
  }
};

/**
 * 渲染选中的人物列表
 */
export const renderSelectedNurses = () => {
  const container = document.getElementById('selectedNursesContainer');
  const list = document.getElementById('selectedNursesList');
  
  if (!container || !list) return;
  
  // 清空列表
  list.innerHTML = '';
  
  // 渲染选中的人物
  if (state.selectedNurses.length > 0) {
    state.selectedNurses.forEach((nurse) => {
      const item = document.createElement('div');
      item.className = 'selected-nurse-item';
      
      const text = document.createElement('span');
      text.textContent = `${nurse.job}：${nurse.name}`;
      
      const deleteBtn = document.createElement('button');
      deleteBtn.className = 'delete-btn';
      deleteBtn.textContent = '删除';
      deleteBtn.onclick = (e) => {
        e.stopPropagation();
        import('./handlers.js').then(({ removeSelectedNurse }) => {
          removeSelectedNurse(nurse.id);
        });
      };
      
      item.appendChild(text);
      item.appendChild(deleteBtn);
      list.appendChild(item);
    });
  }
  
  // 始终显示容器（即使没有选中的人物，也要显示按钮）
  container.style.display = 'block';
};

